package miniMVC.patterns
{
	import flash.events.EventDispatcher;
	
	import miniMVC.i.IRichDispatcher;

	/**
	 * 监听者地图
	 * 消息和对应的函数绑定的数组,本组件用于扩展EventDispatcher
	 * 使用本组件能够删除对象所有消息的绑定,或者删所有消息
	 * @author Pelephone
	 */
	public dynamic class ListenerMgr extends EventDispatcher implements IRichDispatcher
	{
//		private var eventDispatcher:IEventDispatcher;
		
		public function ListenerMgr()
		{
//			eventDispatcher = target;
		}
		
		/**
		 * 将消息监听的绑定数据存在此对象里面
		 * @param type
		 * @param listener
		 */
		public function addListener(type:String, listener:Function
									, priority:int=0, useWeakReference:Boolean=false):void
		{
//			eventDispatcher.addEventListener(type,listener,useCapture,priority,useWeakReference);
			var ls:Array = getTypeListeners(type);
			if(!ls) this[type] = [];
			this[type].push(listener);
		}
		
		/**
		 * 移除某消息跟某事件的绑定
		 * @param type
		 * @param listener
		 */
		public function removeListener(type:String, listener:Function):void
		{
			var ls:Array = getTypeListeners(type);
			if(!ls) return;
			var lid:int = ls.indexOf(listener);
			if(lid>=0) ls.splice(lid,1);
			if(!ls.length) delete this[type];
		}
		
		/**
		 * 获取某消息绑定的所有方法
		 */
		public function getTypeListeners(type:String):Array
		{
			return this[type] as Array;
		}
		
		/**
		 * 移除某消息的所有监听方法
		 * @param type
		 */
		public function removeTypeListeners(type:String):void
		{
			this[type] = null;
			delete this[type];
		}
		
		/**
		 * 移除所有消息绑定
		 */
		public function removeAllListeners():void
		{
			for each (var type:String in this) 
			{
				removeTypeListeners(type);
			}
		}
	}
}